#include "../../includes/controller/Logger.h"

namespace controller
{
	QTextStream Logger::outputStream;
	QMutex Logger::mutex;

	void Logger::setOutput( FILE *f )
	{
		QFile *ff = new QFile();

		ff->open( f, QIODevice::WriteOnly );

		outputStream.setDevice( ff );
	}

	void Logger::write( const char *message )
	{
		QString m( message );
		Logger::write( m );
	}

	void Logger::write( const int &i )
	{
		QString m = QString( "%1" ).arg( i );

		Logger::write( m );
	}

	void Logger::write( const bool &b )
	{
		QString m = QString( "%1" ).arg( b );
		Logger::write( m );
	}

	void Logger::write( const QString &message )
	{
		QString dateMessage;
		QDateTime data = QDateTime::currentDateTime();

		if( message != "" )
		{
			dateMessage = "dd/M/yyyy hh:mm:ss - %1";
			dateMessage = data.toString( dateMessage ).arg( message );
		} else
		{
			dateMessage = "";
		}

		// Area critica, evitar concorrencia ao acesso a fila de mensagens
		Logger::mutex.lock();

		outputStream << message << '\n';

		outputStream.flush();

		Logger::mutex.unlock();
	}
}
